package cn.tedu.vrd07.controller;

import cn.tedu.vrd07.entity.Banner;
import cn.tedu.vrd07.mapper.BannerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class BannerController {
    @Autowired(required = false)
    BannerMapper mapper;
    @Value("${dirPath}")
    private String dirPath;
    @RequestMapping("/banner/select")
    public List<Banner> select(){
        return mapper.select();
    }
    @RequestMapping("/banner/delete")
    public void delete(int id){
        //删除数据之前删除文件
        String url=mapper.selectUrlById(id);
        //得到文件完整的磁盘路径
        String filePath =dirPath+url;
        //删除文件
        new File(filePath).delete();
        mapper.delete(id);
    }
    @RequestMapping("/banner/insert")
    public void insert(MultipartFile picFile) throws IOException {
        String fileName =picFile.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        File dirFile =new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath =dirPath+"/"+fileName;
        picFile.transferTo(new File(filePath));
        Banner banner=new Banner();
        banner.setUrl("/"+fileName);
        mapper.insert(banner);
    }
}
